package com.yz.jdd.module.main.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.JsonObject;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.yunzong.wifi.netconfig.SmartConfig;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseFragment;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.StringUtil;
import com.yz.jdd.module.cashier.CashierActivity;
import com.yz.jdd.module.login.view.LoginActivity;
import com.yz.jdd.module.scan.view.ScanActivity;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.photo.utils.TConstant;
import com.yz.jdd.service.PlayerMusicService;
import com.yz.jdd.webview.H5BridgeActivity;
import com.yz.jdd.webview.HostJsScope;
import com.yz.jdd.webview.net.H5Subscription;
import com.yz.jdd.widget.TopDialog;

import java.util.ArrayList;
import java.util.List;

public class UserFragment extends BaseFragment{
    public static final String TAG = "lkf";
    private BridgeWebView webview; //webview
    private LinearLayout errorLayout;
    private String main_url = "";//跳转到该页面的url 由上一个页面返回
    private List<String> apiQueue = new ArrayList<String>();
    private EditText editText;
    private Button button;
    private Button scan;
    LinearLayout loading_layout;

    RelativeLayout top_bar;
    TextView title;
    TextView rightTextView;
    SmartConfig smartConfig;

    private MyRecriver myRecriver;
    private IntentFilter intentFilter;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        init(view);
        myRecriver = new MyRecriver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("updateH5Page");
        requireActivity().registerReceiver(myRecriver, intentFilter);
    }

    // 多进程,广播接收消息
    class MyRecriver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content = intent.getStringExtra("event");
            if (!StringUtil.isEmpty(content)) {
                if (Events.EVENT_VOICE_BROADCAT.equals(content)) {
                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.NEW_ORDER_EVENT);");
                        }
                    });
                }
            } else {
                if (Events.EVENT_LOAD_URL.equals(content)) {
                    dismissLoading();
                    webview.loadUrl(main_url);
                }
            }
        }
    }


    private void init(View view) {
        String sessionId = requireActivity().getIntent().getStringExtra("sessionId");
        if (!PreferencesUtils.getString(requireActivity(), BaseConfigs.PREF_SESSIONID, "").equals(sessionId)) {
            if (!TextUtils.isEmpty(sessionId)) {
                PreferencesUtils.putString(requireActivity(), BaseConfigs.PREF_SESSIONID, sessionId);
            }
        }

        loading_layout = (LinearLayout) view.findViewById(R.id.loading_layout);

        String loading = requireActivity().getIntent().getStringExtra("loading");
        if (!TextUtils.isEmpty(loading)) {
            loading_layout.setVisibility(View.GONE);
        }

        editText = (EditText) view.findViewById(R.id.edittext);
        button = (Button) view.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(editText.getText().toString())) {
                    webview.loadUrl(editText.getText().toString() + "?android=4.1&statusBarHeight=40");
                }
            }
        });
        scan = (Button) view.findViewById(R.id.scan);
        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(requireActivity(), ScanActivity.class));
            }
        });
        top_bar = (RelativeLayout) view.findViewById(R.id.top_bar);


        title = (TextView) view.findViewById(R.id.title);


        rightTextView = (TextView) view.findViewById(R.id.right);

        webview = (BridgeWebView) view.findViewById(R.id.webview);
        errorLayout = (LinearLayout) view.findViewById(R.id.error_layout);
        errorLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isErrorPage = false;
                webview.reload();
            }
        });
        Bundle args = getArguments();
        if (args != null) {
            main_url = args.getString(Constants.H5_WEB_URL, "");
        }
        initWebView();
    }


    @Override
    public void onResume() {
        super.onResume();
        //界面被唤醒的时候调用
        Log.i("lkf", "onResume");
        if (webview != null) {
            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.RESUME_EVENT);");
        }
        if (getActivity() != null) {
            getActivity().stopService(new Intent(requireActivity(), PlayerMusicService.class));
        }
    }

    private void initWebView() {
        /**
         * 规则在定义请求接口的时候需要首先调用,apiQueue.add("getrequest"); 因为js会首先调用checkApi接口
         * 检验Android本地方法是否存在
         */
//        apiQueue.add("openNativePage");
        apiQueue.add("logout");
        apiQueue.add("dial");
        apiQueue.add("sendHttpRequest"); //发送http请求

        // 设置具体WebViewClient
        webview.setWebViewClient(new MyWebViewClient(webview));
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {

            }


            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (title.contains("404")) {
                    showErrorPage();
                }
            }
        });
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAllowFileAccessFromFileURLs(true);
        webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setDefaultTextEncodingName("utf-8");


        //极速云所需配置
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//支持js调用window.open方法
        webview.getSettings().setSupportMultipleWindows(false);// 设置允许开启多窗口
        String ua = webview.getSettings().getUserAgentString();
        webview.getSettings().setUserAgentString(ua + ";androidapp/cross-bmios" + ";webJSY/1.0.0");


        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.LOW);
        webview.getSettings().setTextSize(WebSettings.TextSize.NORMAL);

        webview.getSettings().setTextZoom(100);
        webview.loadUrl(main_url);


        //////////////////////////////////////////////////跳转登录关闭其他页面
        webview.registerHandler("checkApi", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                Response_Base response_base = new Response_Base();
                String code = "";
                String msg = "";
                boolean success;
                if (jsonObject != null && jsonObject.get("apiName") != null) {
                    String str = jsonObject.get("apiName").getAsString();
                    Log.i("lkf", "apiName=" + str);
                    if (!TextUtils.isEmpty(str) && apiQueue.contains(str)) {
                        //说明接口存在
                        code = "0";
                        msg = "支持该接口";
                        success = true;

                    } else {
                        //接口不存在
                        code = "-1";
                        msg = "接口不存在";
                        success = false;
                    }
                } else {
                    //data格式有问题
                    code = "-1";
                    msg = "数据格式有问题";
                    success = false;
                }
                response_base.setResultObject(null);
                HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "checkApi", response_base, function);

            }
        });
        webview.registerHandler("sendHttpRequest", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                HostJsScope jsScope = new HostJsScope();
                jsScope.resultCallBack(webview, "sendHttpRequest", data, function);
            }
        });
        webview.registerHandler("dial", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        if (TextUtils.isEmpty(data))
                            return;
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        if (jsonObject != null && jsonObject.get("mobile") != null) {
                            String str = jsonObject.get("mobile").getAsString() + "";
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            Response_Base response_base = new Response_Base();
                            response_base.setCode("0");
                            response_base.setSuccess(true);
                            response_base.setResultObject(null);
                            HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "dial", response_base, function);
                        }

                    }
                });

        webview.registerHandler("logout", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                H5Subscription.h5LogoutSubscription(new ApiCallback() {
                    @Override
                    public void onSuccess(Response_Base response_baseModel) {
                        PreferencesUtils.putString(requireActivity(), BaseConfigs.STRING_MOVEKOUBEI, "0");
                        RxBus.getInstance().send(Events.EVENT_302CODE, "");
                        Intent intent = new Intent(requireActivity(), LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("logout", "1");
                        startActivity(intent);
                        Response_Base response_base = new Response_Base();
                        response_base.setCode("0");
                        response_base.setSuccess(true);
                        response_base.setResultObject(null);
                        HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "logout", response_base, function);
                    }

                    @Override
                    public void onNeedLogin(String msg) {
                    }

                    @Override
                    public void onFail(Response_Base response_baseModel) {
                        if (response_baseModel != null) {
                            String msg = response_baseModel.getMsg();
                            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, "logout", "", function);
                        }
                    }
                });

            }
        });

    }

    /**
     * 自定义的WebViewClient
     */
    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!isErrorPage) {
                hideErrorPage();
            }

            view.loadUrl("javascript:window.YzJSBridge = window.WebViewJavascriptBridge;window.YzJSBridge.call = window.YzJSBridge.callHandler;");
            view.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.READY_EVENT);");
            view.loadUrl("javascript:readyFunc();");
            loading_layout.setVisibility(View.GONE);
            dismissLoading();

        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.i("lkf", failingUrl + "onReceivedError==" + description + "     errorCode" + errorCode);
            showErrorPage();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("taobao://")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);

                return true;
            }
            if (url.trim().startsWith("tel")) {//特殊情况tel，调用系统的拨号软件拨号【<a href="tel:1111111111">1111111111</a>】
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }


            return super.shouldOverrideUrlLoading(view, url);

        }

    }

    private boolean isErrorPage;//默认false 说明不是错误页面

    public void showErrorPage() {
        errorLayout.setVisibility(View.VISIBLE);
        webview.setVisibility(View.GONE);
        isErrorPage = true;
    }

    public void hideErrorPage() {
        errorLayout.setVisibility(View.GONE);
        webview.setVisibility(View.VISIBLE);
    }



    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(requireActivity());
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        requireActivity().startService(new Intent(requireActivity(), PlayerMusicService.class));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (smartConfig != null) {
            smartConfig.stop();
        }
        if (webview != null) {
            webview.destroy();
        }
        if (myRecriver != null) {
            requireActivity().unregisterReceiver(myRecriver);
        }
    }
}
